<template>
	<view>
		<!--导航栏-->
		<pageLayout
			:barTitle="title"
			:isSearchNull="isSearchNull"
			:isOpen="isOpen"
			@rightClick="clickSearch">
		</pageLayout>
		<!--查询弹窗-->
		<up-popup :z-index="90" :show="isOpen" @close="closeSearch" mode="top">
			<scroll-view class="search" scroll-y="true" @touchmove.stop>
				<view class="search-form">
					<uni-forms ref="searchRef" :modelValue="searchModel" label-width="160rpx">
						<uni-forms-item label="调拨单号">
							<uni-easyinput v-model="searchModel.number" placeholder="请输入调拨单号" />
						</uni-forms-item>
						<uni-forms-item label="发起仓库">
							<uni-easyinput v-model="searchModel.formWarehouseName" placeholder="请输入发起仓库" />
						</uni-forms-item>
						<uni-forms-item label="目的仓库">
							<uni-easyinput v-model="searchModel.destinationWarehouseName" placeholder="请输入目的仓库" />
						</uni-forms-item>
						<uni-forms-item label="调拨状态">
							<uni-data-select
								v-model="searchModel.status"
								placeholder="请选择调拨状态"
								:localdata="allStatusList"></uni-data-select>
						</uni-forms-item>
						<uni-forms-item label="开始时间">
							<uni-datetime-picker type="datetime" placeholder="请选择开始时间" v-model="searchModel.startTime"/>
						</uni-forms-item>
						<uni-forms-item label="结束时间">
							<uni-datetime-picker type="datetime" placeholder="请选择结束时间" v-model="searchModel.endTime"/>
						</uni-forms-item>
					</uni-forms>
					<view class="search-footer main-flex">
						<up-button
							class="search-footer-item"
							text="搜索"
							type="primary"
							@click="searchSubmit"
							icon="search"></up-button>
						<up-button
							class="search-footer-item"
							@click="resetSubmit"
							form-type="reset"
							text="重置"></up-button>
					</view>
				</view>
			</scroll-view>
		</up-popup>
		<view class="content">
			<!--操作-->
			<view class="operate main-flex">
				<view class="operate-item" v-if="checkPermi(['zhouyz:warehouseAllocation:add'])">
					<up-button
						class="operate-btn main-flex"
						size="mini"
						type="primary"
						@click="addFun">
						<uni-icons class="operate-btn-icon" type="plusempty" size="28rpx" color="#ffffff"></uni-icons>
						<view class="operate-btn-text">新增调拨单</view>
					</up-button>
				</view>
			</view>
			<!--内容-->
			<view class="table">
				<ty-table
					:data="tableList"
					:columns="columns"
					:sortable="true"
					@row-click="rowClick"
					:cellClassName="() => 'table-cell'"
					:headerCellClassName="() => 'table-cell'"
					:rowClassName="() => 'table-row'"
					:isOperateBtn="(row) => {
						return (checkPermi(['zhouyz:warehouseAllocation:form']) && row.status === 1) ||
						(checkPermi(['zhouyz:warehouseAllocation:destination']) && row.status === 2) || 
						(checkPermi(['zhouyz:warehouseAllocation:destination']) && row.status === 3) ||
						(checkPermi(['zhouyz:warehouseAllocation:remove']) && row.status === 0)
					}"
					stripe
					border>
					<template v-slot:left="{ row }">
						<view class="table-td-cell">
							<view class="table-td-row">调拨单：<text class="table-td-text">{{row.number}}</text></view>
							<view class="table-td-row">发起仓库：<text class="table-td-text">{{row.formWarehouseName}}</text></view>
							<view class="table-td-row">发货仓库：<text class="table-td-text">{{row.formWarehouseName}}</text></view>
							<view class="table-td-row">目的仓库：<text class="table-td-text">{{row.destinationWarehouseName}}</text></view>
							<view class="table-td-row">调拨状态：<uni-tag size="small" :text="arrText(allStatusList, row.status)" /></view>
						</view>
					</template>
					<template v-slot:right="{ row }">
						<view class="table-td-cell">
							<view class="table-td-row">发起时间：<text class="table-td-text">{{row.createTime}}</text></view>
							<view class="table-td-row">发货时间：<text class="table-td-text">{{row.sendTime}}</text></view>
							<view class="table-td-row">到货时间：<text class="table-td-text">{{row.arriveTime}}</text></view>
							<view class="table-td-row">调拨说明：<text class="table-td-text">{{row.remark}}</text></view>
						</view>
					</template>
					<template v-slot:operate="{ row }">
						<view class="table-td-operate table-cell table-td-row main-flex">
							<view class="table-operate-btn main-flex" v-if="checkPermi(['zhouyz:warehouseAllocation:form']) && row.status === 1">
								<up-button
									size="mini"
									type="primary"
									@click.stop="sendFun(row.id)">
									<view class="table-operate-btn-text">确认发货</view>
								</up-button>
							</view>
							<view class="table-operate-btn main-flex" v-if="checkPermi(['zhouyz:warehouseAllocation:destination']) && row.status === 2">
								<up-button
									class="table-operate-btn main-flex"
									size="mini"
									type="warning"
									@click.stop="receiptFun(row.id)">
									<view class="table-operate-btn-text">确认收货</view>
								</up-button>
							</view>
							<view class="table-operate-btn main-flex" v-if="checkPermi(['zhouyz:warehouseAllocation:destination']) && row.status === 3">
								<up-button
									class="table-operate-btn main-flex"
									size="mini"
									type="warning"
									@click.stop="joinFun(row.id)">
									<view class="table-operate-btn-text">商品入库</view>
								</up-button>
							</view>
							<view class="table-operate-btn main-flex" v-if="checkPermi(['zhouyz:warehouseAllocation:remove']) && row.status === 0">
								<up-button
									class="table-operate-btn main-flex"
									size="mini"
									type="error"
									@click.stop="deleteFun(row.id)">
									<uni-icons class="table-operate-btn-icon" type="trash" size="20rpx" color="#ffffff"></uni-icons>
									<view class="table-operate-btn-text">删除</view>
								</up-button>
							</view>
						</view>
					</template>
					<template v-slot:empty>
						<view class="table-empty">
							<up-empty mode="data"/>
						</view>
					</template>
				</ty-table>
			</view>
			<!--分页-->
			<view class="pagination" v-show="total > 0">
				<ty-pagination
					:total="total"
					:pageSize="pageSize"
					:currentPage="pageNum"
					:pageSizes="[10, 20, 30, 50]"
					mode="simple"
					layout="first,prev,page,next,last"
					@sizeChange="sizeChange"
					@change="pageChange">
				</ty-pagination>
			</view>
		</view>
	</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { computed, onMounted, ref } from 'vue'
import { tab, auth, modal } from "@/plugins"
import { getTitle } from "@/utils/getter"
import { allocationStatus } from "@/api/system/dict/data"
import { checkPermi, checkRole, checkOnlyPermi, checkOnlyRole } from "@/utils/permission"
import { warehouseAllocation, warehouseAllocationJoin, warehouseAllocationDel, warehouseAllocationSend, warehouseAllocationGit } from "@/api/erp_api/warehouse"
import { isObjectEmptySimple, copyText, arrText, getEdgeMonthFirstDay, getRecentDays } from '@/utils/ty.js';
import useUserStore from '@/store/modules/user'

	const userStore = useUserStore()
	// 标题设置
	const title = ref('')
	onLoad((option) => {
		title.value = getTitle(userStore.menu)
		uni.setNavigationBarTitle({
			title: title.value 
		})
		uni.$on('refreshList', () => {
			getList()
		})
	})
	
	const allStatusList = ref([])
	const getAllocationStatus = () => {
		allocationStatus().then(res => {
			allStatusList.value = res.data.map(item => {
				return {
					...item,
					value: item.dictValue,
					text: item.dictLabel
				}
			}) || []
    })
	}
	
	// 搜索相关
	const isSearchNull = ref(true)
	const isOpen =  ref(false)
	const clickSearch = (val) => {
		isOpen.value = val
	}
	const closeSearch = (val) => {
		isOpen.value = false
	}
	// 确认搜索
	const searchRef = ref(null)
	const searchModel = ref({
		formWarehouseName: '',
		number: '',
		destinationWarehouseName: '',
		status: '',
		startTime: `${getRecentDays(15)} 00:00:00`,
		endTime: getEdgeMonthFirstDay(1)
	})
	const searchSubmit = () => {
		pageNum.value = 1
		tableList.value = []
		isOpen.value = false
		searchFirst()
	}
	// 重置搜索
	const resetSubmit = () => {
		// searchRef.value.resetFields()
		searchModel.value = {
			formWarehouseName: '',
			number: '',
			destinationWarehouseName: '',
			status: '',
			startTime: `${getRecentDays(15)} 00:00:00`,
			endTime: getEdgeMonthFirstDay(1)
		}
		isSearchNull.value = true
		isOpen.value = false
		searchFirst()
	}
	
	
	// 数据查询
	const pageNum = ref(1)
	const pageSize = ref(10)
	const total = ref(0)
	const tableList = ref([])
	const isLoading = ref(false)
	
	// 表格头部
	const columns = ref([
		{ title: '批次信息', key: 'left' },
		{ title: '商品数量', key: 'right' }
	])
	
	// 从第一页查询
	const searchFirst = () => {
		pageNum.value = 1
		tableList.value = []
		isSearchNull.value = isObjectEmptySimple(searchModel.value)
		getList()
	}
	//页数切换
	const pageChange = (page) => {
		pageNum.value = page
		getList()
	}
	//每页条数切换
	const sizeChange = (size) => {
		pageSize.value = size
		getList()
	}
	
	const getList = () => {
		const params = {
			pageNum: pageNum.value,
			pageSize: pageSize.value
		}
		if (searchModel.value.formWarehouseName) {
			params.formWarehouseName = searchModel.value.formWarehouseName
		}
		if (searchModel.value.destinationWarehouseName) {
			params.destinationWarehouseName = searchModel.value.destinationWarehouseName
		}
		if (searchModel.value.status || searchModel.value.status === 0) {
			params.status = searchModel.value.status
		}
		if (searchModel.value.number) {
			params.number = searchModel.value.number
		}
		if (searchModel.value.startTime) {
			params.startTime = searchModel.value.startTime
		}
		if (searchModel.value.endTime) {
			params.endTime = searchModel.value.endTime
		}
		isLoading.value = true
		uni.showLoading({
			title: '数据加载中...'
		})
		warehouseAllocation(params).then(res => {
			tableList.value = res.rows || []
			total.value = res.total
			isLoading.value = false
			uni.hideLoading()
    }).catch(() => {
			isLoading.value = false
			uni.hideLoading()
		})
	}
	
	// 点击行
	const rowClick = (row) => {
		uni.navigateTo({
			url: `/pages/warehouse/warehouseAllocationInfo?id=${row.id}`
		})
	}
	
	// 新增采购单
	const addFun = () => {
		uni.navigateTo({
			url: '/pages/warehouse/warehouseAllocationAdd'
		})
	}
	
	//确认发货
	const sendFun = (id) => {
		uni.showModal({
			title: '确认发货',
			content: `请确保发货商品与【详情】里的商品、批次号、和数量准确！`,
			success: function (res) {
				if (res.confirm) {
					warehouseAllocationSend({
						id
					}).then(res => {
						modal.showToast('发货成功')
						getList()
					}).catch((err) => {
						modal.showToast(err)
					})
				}
			}
		})
	}
	
	//确认收货
	const receiptFun = (id) => {
		uni.showModal({
			title: '确认收货',
			content: `请确保收货商品与【详情】里的商品、批次号、和数量准确！`,
			success: function (res) {
				if (res.confirm) {
					warehouseAllocationGit({
						id
					}).then(res => {
						modal.showToast('收货成功')
						getList()
					}).catch((err) => {
						modal.showToast(err)
					})
				}
			}
		})
	}
	
	//商品入库
	const joinFun = (id) => {
		uni.showModal({
			title: '商品入库',
			content: `请确保入库商品与【详情】一致，如果不一致，可以在入库后相互调拨！`,
			success: function (res) {
				if (res.confirm) {
					warehouseAllocationJoin({
						id
					}).then(res => {
						modal.showToast('收货成功')
						getList()
					}).catch((err) => {
						modal.showToast(err)
					})
				}
			}
		})
	}
	
	//删除
	const deleteFun = (id) => {
		uni.showModal({
			title: '删除',
			content: `是否确认删除仓库调拨编号为"${id}"的数据项?`,
			success: function (res) {
				if (res.confirm) {
					warehouseAllocationDel({
						id
					}).then(res => {
						modal.showToast('删除成功')
						getList()
					}).catch((err) => {
						modal.showToast(err)
					})
				}
			}
		})
	}
	
	onMounted(async () => {
		await getAllocationStatus()
		searchFirst()
	})
</script>

<style scoped>
.form {
	background-color: #fff;
}
.record-type-0 {
	background-color: #e7faf0;
	border-color: #d0f5e0;
	color: #13ce66;
	padding: 2px 6px !important;
}
.record-type-1 {
	background-color: #ffeded;
	border-color: #ffdbdb;
	color: #ff4949;
	padding: 2px 6px !important;
}
</style>
